package cn.bjc.basic.cotroller;

import cn.bjc.basic.util.FastDfsUtils;
import cn.bjc.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {
    
    /*
        上传的接口
        @RequestPart 接收的是一个文件
        required = true :必须上传一个图片
     */
    @PostMapping
    public JsonResult upload(@RequestPart(value = "file") MultipartFile file){
        try {
            //获取原始file文件名
            String originalFilename = file.getOriginalFilename();
            
            //从原始file文件名中获取file文件后缀,不要"."
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
           
            //调用工具类中的upload方法
            String path = FastDfsUtils.upload(file.getBytes(), substring);

            //把path设置给jsonResult中的resultObj属性
            return JsonResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("上传失败");
        }
    }
    
    
    /*
        删除的接口
        /common/fastDfs/?path= +filePath
     */
    @DeleteMapping
    public JsonResult delete(@RequestParam(value = "path") String path){
        try {
            //调用工具类中的delete方法
            //path:/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            //需要截取出来group1      M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String pathTmp = path.substring(1); //  group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //  gr123oup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);//    M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            FastDfsUtils.delete(groupName, remotePath);
            
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }
    
    
}
